package com.qf.user.factory.registerfactory;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.core.entity.User;
import com.qf.common.core.exception.CustomerException;
import com.qf.common.redis.utils.RedisUtil;
import com.qf.user.mapper.UserMapper;
import com.qf.user.param.RegisterParam;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zdl
 * @date 2025/3/22
 */
@Service
public class UserNameAndPassWordRegistration implements Registration {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public int register(RegisterParam registerParam) { //必传参数: username, password, phone, code,type=1
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, registerParam.getUsername()));
        if (user != null) {
            throw new CustomerException("5001", "用户名已存在");
        }
        List<User> u = userMapper.selectList(Wrappers.lambdaQuery(User.class).eq(User::getPhone, registerParam.getPhone()));
        if (!u.isEmpty()) {
            throw new CustomerException("5001", "当前手机号已注册");
        }
        //从redis中取出验证码
        String cacheCode = redisUtil.getCacheObject(registerParam.getPhone());
        if (cacheCode == null) {
            throw new CustomerException("5002", "验证码已过期");
        }
        if (!cacheCode.equals(registerParam.getCode())) {
            throw new CustomerException("5003", "验证码错误");
        }
        //注册用户
        user = new User();
        user.setUsername(registerParam.getUsername());
        user.setPassword(SecureUtil.md5(registerParam.getPassword()));
        user.setPhone(registerParam.getPhone());
        return userMapper.insert(user) == 0 ? 0 : 1;
    }
}
